import axios from 'axios'
import router from '@/router/index.js'
import { Message } from "element-ui";
import Vue from 'vue'

//基本配置
axios.defaults.withCredentials = true;
axios.defaults.timeout = 10000;
axios.defaults.baseURL = process.env.VUE_APP_ADMIN_BASE_URL;

//请求拦截器
axios.interceptors.request.use(function (config) {
	if (sessionStorage.getItem('token')) {
		config.headers.Authorization = sessionStorage.getItem('token');
	}
	return config;
}, function (error) {
	return Promise.reject(error);
});

//响应拦截器
axios.interceptors.response.use(function (response) {
	return response;
}, function (error) {
	if (error.response) {
		if (error.response.status == 404) {
			MsgAlert('很抱歉，资源未找到!');
		}
		if (error.response.status == 401 || error.response.data.code === 401) {
			MsgAlert('登陆已失效，请重新登陆');
			setTimeout(() => { router.push('/login'); }, 1000);
		}
	} else {
		MsgAlert('请检查您的网络连接！');
	}
	return Promise.reject(error);
});

//错误提示
function MsgAlert(e) {
	Message.closeAll();
	Message.error(e);
}

// 接口调用成功结果处理
function handleSuccess(res, resolve) {
	// 如果接口返回的code值为401,表示用户token过期，需要重新登陆
	if (res.data.code === 401) {
		// 提示
		MsgAlert('登陆已失效，请重新登陆');
		// 清空浏览器token

		// 跳转到登陆页
		setTimeout(() => { router.push('/login'); }, 1500);
	} else if (res.data.code === 200) {
		// 结果正常处理
		resolve(res)
	} else {
		// 其他错误，弹窗提示
		MsgAlert(res.data.msg);
	}
}

//获取token
function getToken() {
	return sessionStorage.token ? sessionStorage.token : "";
}

//异步请求方法
var https = {
	get: function (url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: "GET",
				url: url,
				params: params,
				headers: {
					token: getToken()
				}
			})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
					// MsgAlert(err);
				});
		});
	},
	postJson: function (url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: "POST",
				url: url,
				data: JSON.stringify(params),
				headers: {
					"Content-Type": "application/json",
					token: getToken()
				}
			})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
					// MsgAlert(err);
				});
		});
	},
	// post方法,application/x-www-form-urlencoded序列化方式传递，参数形式未定
	postXform: function (url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: "POST",
				url: url,
				data: transformRequest(params),
				headers: {
					"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
					token: getToken()
				}
			})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
					// MsgAlert(err);
				});
		});
	},
	// 表单文件上传
	fileUpload: function (url, params = {}) {
		return new Promise((resolve, reject) => {
			axios({
				method: "POST",
				url: url,
				data: params,
				headers: {
					"Content-Type": "multipart/form-data",
					token: getToken()
				}
			})
				.then(res => {
					handleSuccess(res, resolve);
				})
				.catch(err => {
					reject(err);
					// MsgAlert(err);
				});
		});
	}
}

/**
 * 参数序列化
 * return 参数序列化结果
 */
function transformRequest(obj) {
	if (obj !== {} || obj !== null || obj !== '') {
		var str = [];
		for (var p in obj) {
			if (obj[p] instanceof Array) {
				obj[p].forEach(element => {
					str.push(encodeURIComponent(p) + "[]=" + encodeURIComponent(element));
				});
			} else {
				if (obj[p] !== undefined && obj[p] !== null) {
					//注：这里必须讲 false 排除在外，否则传入实际false将跳过处理。
					str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
				}
			}
		}
		return str.join("&");
	}
	return null;
}

export default https;
